#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    isDrawing=false;
    //重设窗口大小
    resize(600,500);
    //设置画布大小
     pix=QPixmap(200,200);
pix.fill(Qt::white);

    isDrawing=false;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void  MainWindow::paintEvent(QPaintEvent *){
int x,y,h,w;
  x=lastpoint.x();
  y=lastpoint.y();
  w=endtpoint.x()-x;
  h=endtpoint.y()-y;

  //绘图设备
  QPainter pait(this);
  if(isDrawing)
  {
      //将pix 复制到 tmpPix(补助画布)中 保存让以前 的画不消失
      tmpPix=pix;
      QPainter pp(&tmpPix);
      pp.drawRect(x,y,w,h);
      pait.drawPixmap(0,0,tmpPix);
  }
  else{

      QPainter  pp(&pix);
      pp.drawRect(x,y,w,h);
      pait.drawPixmap(0,0,pix);
  }

}

void  MainWindow::mousePressEvent(QMouseEvent *event){
    if(event->button()==Qt::LeftButton){
        lastpoint==event->pos();
        isDrawing=true;
        update();
    }
}

void  MainWindow::mouseReleaseEvent(QMouseEvent *event){
    if(event->button()==Qt::LeftButton)
    {


        endtpoint=event->pos();
        isDrawing=false;
        update();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{

    if(event->buttons()==Qt::LeftButton)
    {

        endtpoint=event->pos();
        update();
    }
}
